<template>
  <div class="container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>试题录入</span>
      </div>
      <div>
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="120px"
          class="demo-ruleForm"
          width="200px"
        >
          <!-- 学科 -->
          <el-form-item label="学科：" prop="subjectID">
            <el-select
              v-model="ruleForm.subjectID"
              placeholder="请选择"
              style="width: 400px;"
              @change="getQuestionLabel"
            >
              <el-option
                :key="item.id"
                v-for="item in subjectList"
                :label="item.subjectName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 目录 -->
          <el-form-item label="目录：" prop="catalogID">
            <el-select
              v-model="ruleForm.catalogID"
              placeholder="请选择"
              style="width: 400px;"
            >
              <el-option
                :key="item.value"
                v-for="item in directoryList"
                :label="item.label"
                :value="item.value"
              ></el-option>
              <el-option label="区域二" value="beijing"></el-option>
            </el-select>
          </el-form-item>
          <!-- 企业 -->
          <el-form-item label="企业：" prop="enterpriseID">
            <el-select
              v-model="ruleForm.enterpriseID"
              placeholder="请选择"
              style="width: 400px;"
            >
              <el-option
                :key="item.id"
                v-for="item in enterpriseList"
                :label="item.company"
                :value="item.id"
              ></el-option>
              <el-option label="区域二" value="beijing"></el-option>
            </el-select>
          </el-form-item>
          <!-- 城市 -->
          <el-form-item label="城市：" prop="province">
            <el-select
              v-model="ruleForm.province"
              placeholder="请选择"
              style="width: 198px;"
              @change="getCity"
            >
              <el-option
                :key="index"
                v-for="(item, index) in provinceList"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
            <el-select
              v-model="ruleForm.city"
              placeholder="请选择"
              style="width: 198px; margin-left: 4px;"
            >
              <el-option
                :key="index"
                v-for="(item, index) in cityList"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 方向 -->
          <el-form-item label="方向：" prop="direction">
            <el-select
              v-model="ruleForm.direction"
              placeholder="请选择"
              style="width: 400px;"
            >
              <el-option
                :key="index"
                v-for="(item, index) in directionList"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 题型 -->
          <el-form-item label="题型：" prop="questionType">
            <el-radio v-model="ruleForm.questionType" label="1">单选</el-radio>
            <el-radio v-model="ruleForm.questionType" label="2">多选</el-radio>
            <el-radio v-model="ruleForm.questionType" label="3">简答</el-radio>
          </el-form-item>
          <!-- 难度 -->
          <el-form-item label="难度：" prop="difficulty">
            <el-radio v-model="ruleForm.difficulty" label="1">简单</el-radio>
            <el-radio v-model="ruleForm.difficulty" label="2">一般</el-radio>
            <el-radio v-model="ruleForm.difficulty" label="3">困难</el-radio>
          </el-form-item>
          <!-- 题干 富文本编辑器 -->
          <el-form-item label="题干：" prop="question">
            <div class="bianjiqi" style="height: 240px;">
              <quill-editor v-model="ruleForm.question"></quill-editor>
            </div>
          </el-form-item>
          <!-- 选项 -->
          <el-form-item
            label="选项："
            class="xuanxiang"
            v-if="ruleForm.questionType === '1'"
          >
            <div
              class="option_item"
              :key="item.id"
              v-for="item in ruleForm.options"
            >
              <el-radio
                v-model="item.isRight"
                @change="isChange(item)"
                :label="true"
                >{{ item.code + '：' }}</el-radio
              >
              <el-input v-model="item.title" style="width: 240px;"></el-input>
              <el-upload
                class="avatar-uploader"
                action="https://jsonplaceholder.typicode.com/posts/"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="imageUrl" :src="item.img" class="avatar" />
                <span>
                  上传图片
                  <div class="macha"><i class="el-icon-circle-close"></i></div>
                </span>
              </el-upload>
            </div>
            <el-button
              type="danger"
              size="small"
              :disabled="ruleForm.questionType === '1'"
              >+增加选项与答案</el-button
            >
          </el-form-item>
          <!-- 多选 -->
          <el-form-item
            label="选项："
            v-if="ruleForm.questionType === '2'"
            class="xuanxiang"
          >
            <div
              class="option_item"
              :key="item.id"
              v-for="item in ruleForm.options"
            >
              <el-checkbox-group v-model="item.isRight">
                <el-checkbox :label="item.code + '：'"></el-checkbox>
              </el-checkbox-group>
              <el-input v-model="item.title" style="width: 240px;"></el-input>
              <el-upload
                class="avatar-uploader"
                action="https://jsonplaceholder.typicode.com/posts/"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="imageUrl" :src="item.img" class="avatar" />
                <span>
                  上传图片
                  <div class="macha"><i class="el-icon-circle-close"></i></div>
                </span>
              </el-upload>
            </div>
            <el-button
              type="danger"
              size="small"
              :disabled="ruleForm.questionType === '1'"
              @click="addOption"
              >+增加选项与答案</el-button
            >
          </el-form-item>
          <!-- 解析视频 -->
          <el-form-item label="解析视频：" prop="name">
            <el-input
              v-model="ruleForm.videoURL"
              style="width: 400px;"
            ></el-input>
          </el-form-item>
          <!-- 答案解析 富文本编辑器 -->
          <el-form-item label="答案解析：" prop="answer">
            <div class="bianjiqi" style="height: 240px;">
              <quill-editor v-model="ruleForm.answer"></quill-editor>
            </div>
          </el-form-item>
          <!-- 题目备注 -->
          <el-form-item label="题目备注：">
            <el-input
              type="textarea"
              v-model="ruleForm.remarks"
              style="width: 400px;"
            ></el-input>
          </el-form-item>
          <!-- 试题标签 -->
          <el-form-item label="试题标签：" prop="tags">
            <el-select
              v-model="ruleForm.tags"
              placeholder="请选择试题标签"
              style="width: 400px;"
            >
              <el-option
                :key="item.value"
                v-for="item in questionlabelList"
                :label="item.label"
                :value="item.label"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 确认提交按钮 -->
          <el-form-item>
            <el-button type="primary" @click="submitForm()">确认提交</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import { list } from '@/api/hmmm/subjects' // 学科
import { simple } from '@/api/hmmm/directorys' // 目录
import { list as enterpriselist } from '@/api/hmmm/companys' // 企业
import { provinces, citys } from '@/api/hmmm/citys' // 城市 城市下区
import { simple as questionlabellist } from '@/api/hmmm/tags' // 试题标签
import { direction } from '@/api/hmmm/constants' // 方向
import { add, detail } from '@/api/hmmm/questions' // 提交按钮 修改

export default {
  name: 'questions-new',
  data () {
    return {
      ruleForm: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 市
        city: '', // 区
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        options: [], // 选项
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: '', // 试题标签
        delivery: false,
        type: [],
        dialogImageUrl: '',
        dialogVisible: false,
        subject: {}
      },
      imageUrl: '',
      rules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: 'blur' }],
        catalogID: [{ required: true, message: '请选择目录', trigger: 'blur' }],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'blur' }
        ],
        province: [{ required: true, message: '请选择城市', trigger: 'blur' }],
        direction: [{ required: true, message: '请选择方向', trigger: 'blur' }],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'blur' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'blur' }
        ],
        question: [
          { required: true, message: '请输入题干名称', trigger: 'blur' }
        ],
        answer: [
          { required: true, message: '请输入答案解析', trigger: 'blur' }
        ],
        tags: [{ required: true, message: '请选择标签', trigger: 'blur' }]
      },
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        // 上传图片数组
        pics: [],
        // 商品的详情介绍
        goods_introduce: ''
      },
      subjectList: [],
      directoryList: [],
      enterpriseList: [],
      provinceList: [],
      cityList: [],
      questionlabelList: [],
      directionList: [],
      optionss: 4
    }
  },
  created () {
    if (this.$route.query.id) {
      this.getUpdate()
    }
    this.getTestEntry()
    this.getDirectory()
    this.getEnterprise()
    this.getProvince()
    this.getDirection()
    this.addOptionss(this.optionss)
  },
  components: {},
  methods: {
    async getUpdate () {
      const id = this.$route.query.id
      try {
        const { data } = await detail({ id })
        console.log(data)
        this.ruleForm = data
      } catch (err) {
        console.log(err)
      }
    },
    async submitForm () {
      const { data } = await add(this.ruleForm)
      console.log(data)
      this.$refs.ruleForm.resetFields()
      this.$router.push('/questions/list')
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 获取学科列表数据
    async getTestEntry () {
      this.$refs.ruleForm.resetFields()
      const { data } = await list()
      console.log(data)
      console.log(this.$route.query.id)
      this.subjectList = data.items
      this.getQuestionLabel()
    },
    // 获取目录列表数据
    async getDirectory () {
      const { data } = await simple()
      console.log(data)
      this.directoryList = data
      console.log(this.directoryList)
    },
    // 获取企业列表数据
    async getEnterprise () {
      const { data } = await enterpriselist()
      console.log(data)
      this.enterpriseList = data.items
    },
    // 获取城市列表数据
    getProvince () {
      const data = provinces()
      // console.log(data)
      this.provinceList = data
      // console.log(this.provinceList)
    },
    // 获取城市下区列表数据
    getCity () {
      const data = citys(this.ruleForm.province)
      console.log(data)
      this.cityList = data
    },
    // 获取试题标签列表数据
    async getQuestionLabel () {
      const { data } = await questionlabellist(this.ruleForm.subjectID)
      console.log(data)
      this.questionlabelList = data
    },
    // 获取方向列表数据
    getDirection () {
      const data = direction
      console.log(data)
      this.directionList = data
    },
    // 增加或删除数据
    addOption () {
      console.log(this.optionss)
      if (this.optionss < 8) {
        // 当选项小于7个时增加
        this.optionss = this.optionss + 1
        this.ruleForm.options.push({
          id: this.optionss - 1,
          code: String.fromCharCode(65 + this.optionss - 1),
          title: '',
          img: '',
          isRight: false
        })
      } else {
        this.$message.error('要适可而止哦')
      }
    },
    // 自动生成 A 到 Z
    addOptionss (num) {
      console.log(num)
      for (let i = 0; i < num; i++) {
        this.$set(this.ruleForm.options, i, {
          id: i, // 选项id
          code: String.fromCharCode(65 + i), // 选项代码(A的编码是65, B, C, D……)
          title: '', // 选项标题
          img: '', // 选项图片地址
          isRight: false // 选项答案是否正确(初始值都为false【未被选中】)
        })
      }
    },
    // 监听选项单选是否选中
    isChange (data) {
      console.log(data)
      this.ruleForm.options.forEach(item => {
        item.isRight = false
      })
      data.isRight = true
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.container {
  .box-card {
    margin: 20px;
    .bianjiqi {
      height: 240px;
    }
    .el-form-item--medium .el-form-item__content .quill-editor {
      height: 150px;
    }
    .question-new[data-v-1ffc6d31] .ql-editor {
      height: 200px;
    }
  }
  .xuanxiang {
    .avatar-uploader {
      display: inline-block;
      margin-left: 4px;
    }
    .option_item {
      padding: 0 0 20px;
      .el-checkbox-group {
        display: inline-block;
      }
      .el-radio {
        margin-right: 0;
      }
    }
  }
  .option_item .avatar-uploader .el-upload span:hover {
    border-color: #409eff;
  }
  .option_item .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    vertical-align: bottom;
    display: inline-block;
    span {
      border: 1px dashed #d9d9d9;
      position: relative;
      top: -50%;
      left: 0;
      width: 100px;
      height: 60px;
      line-height: 60px;
      display: inline-block;
      border-radius: 6px;
      .macha {
        position: absolute;
        top: -9px;
        right: -9px;
        width: 18px;
        height: 18px;
        background-color: #fff;
        border-radius: 9px;
        .el-icon-circle-close {
          position: absolute;
          font-size: 18px;
          color: #8c939d;
          top: 0;
          left: 0;
        }
      }
    }
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>
